#include <time.h>
#include "unp.h"

int main(int argc, char *argv[])
{
    int srvfd, connfd, addrlen;
    struct sockaddr_in srvaddr, cliaddr, connaddr;
    char buf[MAXLINE];
    time_t now;

    srvfd = Socket(AF_INET, SOCK_STREAM, 0);

    bzero(&srvaddr, sizeof(srvaddr));
    srvaddr.sin_family = AF_INET;
    srvaddr.sin_port = htons(8000);
    srvaddr.sin_addr.s_addr = htonl(INADDR_ANY);

    Bind(srvfd, (SA*)&srvaddr, sizeof(srvaddr));
    Listen(srvfd, 15);
    
    while (1) {
        connfd = Accept(srvfd, (SA*)&cliaddr, &addrlen);
        printf("Receieved from: %s, remote port: %d\n", 
                inet_ntop(AF_INET, &cliaddr.sin_addr, buf, sizeof(buf)),
                ntohs(cliaddr.sin_port));
       
        Getsockname(connfd, (SA*)&connaddr, &addrlen);
        printf("Local addr: %s, local port: %d\n", 
                inet_ntop(AF_INET, &connaddr.sin_addr, buf, sizeof(buf)),
                ntohs(connaddr.sin_port));

        bzero(&cliaddr, sizeof(cliaddr));
        Getpeername(connfd, (SA*)&cliaddr, &addrlen);
        printf("Remote addr: %s, remote port: %d\n", 
                inet_ntop(AF_INET, &cliaddr.sin_addr, buf, sizeof(buf)),
                ntohs(cliaddr.sin_port));

        time(&now);
        snprintf(buf, sizeof(buf), "%.24s\r\n", ctime(&now));
        printf("%s", buf);
        Send(connfd, buf, strlen(buf), 0);
        Close(connfd);
    }
    
    return 0;
}
